<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
  <style>
    #div1{
      width:400px;
      height:400px;
      background:white;
    }
    body{
      margin:0;
      background: black;
    }
  </style>
</head>
<body>
<div id="div1">
  <svg id="svg1" xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
    <polyline points="50 50 200 300 230 300 250 200" stroke="black" stroke-width="5" fill="none">

    </polyline>
  </svg>
</div>
<script>
  window.onload = function(){
    const svgNS = 'http://www.w3.org/2000/svg';
    const oParent = document.getElementById('div1');
    const oSvg = document.getElementById('svg1');

    let oPolyLine = null;
    let pointsNum = '';

    function createTag(tag, objAttr){
      const oTag = document.createElementNS(svgNS, tag);
      for(let attr in objAttr){
        oTag.setAttribute(attr, objAttr[attr]);
      }
      return oTag;
    }

    oSvg.onmousedown = function (ev) {
      ev = ev || window.event;
      if (!oPolyLine) {
        oPolyLine = createTag('polyline', {fill: 'none', stroke: 'red', 'stroke-width': 2});
        oSvg.appendChild(oPolyLine)
      }
      let x = ev.clientX - oParent.offsetLeft;
      let y = ev.clientY - oParent.offsetTop;
      if (pointsNum == '') {
        pointsNum = x + ',' + y;
      } else {
        pointsNum += ',' + x + ',' + y;
      }
      oPolyLine.setAttribute('points', pointsNum);

      const oCircle = createTag('circle', {
        cx: x,
        cy: y,
        r: 5,
        fill: 'white',
        stroke: 'red',
        'stroke-width': 3
      });
      oSvg.appendChild(oCircle)
    };

    oSvg.onmousemove = function (ev) {
      ev = ev || window.event;

      if (oPolyLine) {
        let x = ev.clientX - oParent.offsetLeft;
        let y = ev.clientY - oParent.offsetTop;
        oPolyLine.setAttribute('points', pointsNum + ',' + x + ',' + y);
      }
    };

    /* 点击右键停止折线绘制 */
    oSvg.oncontextmenu = function () {
      oSvg.onmousemove = null;
      return false;
    };
  }
</script>
</body>
</html>
